//
//  ProductDetailViewController.swift
//  weile
//
//  Created by LKM on 16/10/13.
//  Copyright © 2016年 LKM. All rights reserved.
//
import Foundation
import UIKit
import SKPhotoBrowser
import Kingfisher
import Alamofire
import PDFReader
import SVProgressHUD
import SwiftyJSON
import WebKit
//import PYPhotoBrowser

class ProductDetailViewController: BaseViewController,WKScriptMessageHandler ,WKNavigationDelegate{
//    NSString *path = [[NSBundle mainBundle] bundlePath];
//    NSURL *baseURL = [NSURL fileURLWithPath:path];
//    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index1"
//    ofType:@"html"];
//    NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
//    encoding:NSUTF8StringEncoding
//    error:nil];
//    [self.webView loadHTMLString:htmlCont baseURL:baseURL];
    
    var data:ProductDetailTo?;
    
    var pid:String!;
    var webView :WKWebView!;
    override func viewDidLoad() {
        super.viewDidLoad()
        let mWKWebViewConfiguration=WKWebViewConfiguration.init();
        let mWKUserContentController=WKUserContentController.init()
        mWKUserContentController.add(self, name: "onImageTypeClick")
        mWKWebViewConfiguration.userContentController=mWKUserContentController
        
        webView = WKWebView.init(frame: view.bounds, configuration: mWKWebViewConfiguration)
//        webView.frame = view.bounds
        /// 自动对页面进行缩放以适应屏幕
//        webView.scalesPageToFit = true
//        webView.dataDetectorTypes = .all
         webView.backgroundColor = UIColor.clear
        webView.isOpaque = false
        
//        webView.dataDetectorTypes = UIDataDetectorTypes.link
//        LKMLog("=====\(Bundle.main.path(forResource: "html/productDetail", ofType: "html")!)")
//        let url = URL(string:Bundle.main.path(forResource: "html/productDetail", ofType: "html")! )
//        let request = URLRequest(url: url!)
//        webView.loadRequest(request)
       
        
//        webView.delegate = self
        
        webView.navigationDelegate=self
        
        view.addSubview(webView)
        
        
        
        self.navigationItem.rightBarButtonItems = [
            UIBarButtonItem(image: UIImage(named: "ic_share_archive_666"), style: .plain, target: self, action: #selector(loadShareContent)),
            UIBarButtonItem(image: UIImage(named: "ic_like_archive_666"), style: .plain, target: self, action: #selector(likeUpdata))
            
        ]
        
        self.navigationItem.rightBarButtonItems?[0].tintColor=R.colors._535353;
        self.navigationItem.rightBarButtonItems?[1].tintColor=R.colors._535353;
        
        
        webView.load(URLRequest(url: URL(string: Api.host+"/webApp/iOS/productDetail_iOS.html?pid="+pid )! ))
        

        loadData();
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(message.name == "onImageTypeClick"){
            let id:String  = (message.body as! Dictionary)["body"]!
            LKMLog(id)
            onImageTypeClick(id);
        }
    }
    //  ------ WKNavigationDelegate----
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        ViewHelp.showProgressActivity(containView: self.view);
    }
    // 内容返回时。页面载入ok。。我这里加载页面后，里面的js会去加载数据。
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        ViewHelp.hideProgressActivity(containView: self.view);
    }
   
    //页面载入失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        ViewHelp.hideProgressActivity(containView: self.view);
    }
    //WKNavigationDelegate   end
    
    func bindata_like(){
        
        if self.data == nil{
            return;
        }
        
        self.navigationItem.rightBarButtonItems?[1].tintColor = (self.data?.productDetail?.iskeep ?? 0 ) == 0 ? R.colors._535353 : R.colors.base_color;
    }
    
    func loadData(){
        ViewHelp.showProgressActivity(containView: self.view);
        let ts=Api.getProductlDetail(preTaskSerialNumber: nil, id: pid ) { (re:ResponEntity) in
            ViewHelp.hideProgressActivity(containView: self.view);
            guard re.isSuccess() else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)//成功不显示
                return;
            }
            
            self.data=re.data as? ProductDetailTo;
        }
        taskAlls.append(ts);
    }

    
    var isLikeUpdataIng=false;
    func likeUpdata(){
        if self.data == nil{
            return
        }
        if isLikeUpdataIng {
            return
        }
        isLikeUpdataIng=true;
        
        ViewHelp.showProgressActivity(containView: self.view)
        let ts=Api.CollectProduct(preTaskSerialNumber: nil,id:pid) { (re:ResponEntity) in
            self.isLikeUpdataIng=false;
            ViewHelp.hideProgressActivity(containView: self.view);
            //            self.contentScrollView.endRefreshing(at: self.refresher.position);
            ViewHelp.showTipsView(containView: self.view, tips: re.msg)//成功不显示
            guard re.isSuccess() else{
//                ViewHelp.showTipsView(containView: self.view, tips: re.msg)//成功不显示
                return;
            }
            var data = re.getData() as? [String : Any]  ?? [String : Any]();
            LKMLog("\(data)")
            
            self.data?.productDetail?.iskeep = (0 == ( (data["Status"] as? Int)  ?? 1 ) ) ? 1 : 0;
            self.bindata_like();
            
        }
        taskAlls.append(ts);
    }
    
    var isLoadShareContent=false;
    func loadShareContent(){
        
        if(isLoadShareContent){
            return
        }
        isLoadShareContent=true;
        ViewHelp.showProgressActivity(containView: self.view)
        let ts = Api.getProductShare(preTaskSerialNumber: nil, id:pid) { (re:ResponEntity) in
            self.isLoadShareContent=false
            ViewHelp.hideProgressActivity(containView: self.view);
            guard re.isSuccess() else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)//成功不显示
                return;
            }
            
            let o = re.getData() as! ProductShareTo
            
            ActivityRequest.showShardDialogViewController(self,title: o.title,content: o.content,url: o.shareurl,imageUrl: StringHelp.isEmpty(self.data?.productDetail?.proimg ) ? "" : Api.getImageUrl(self.data?.productDetail?.proimg ?? ""),localImage: #imageLiteral(resourceName: "ic_logo"));
            
//            ShareHelp.share(vc: self, text: o.content ?? "", image: Api.getImageUrl(self.data?.productDetail?.proimg ?? "" ), url: o.shareurl ?? "", finsh: { (isSuccess:Bool) in
//                ViewHelp.showTipsView(containView: self.view, tips: isSuccess ? "分享成功" : "分享失败")
//            })
            
        }
    
        taskAlls.append(ts)
    }
    
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }

    
    override func viewDidDisappear(_ animated: Bool) {
        SVProgressHUD.dismiss()
        curDownloadRequest?.cancel()
    }
    
    

    var curDownloadRequest:DownloadRequest?;
    fileprivate func onImageTypeClick(_ id:String){
        ViewHelp.showProgressActivity(containView: self.view);
        let ts = Api.getProductImages(preTaskSerialNumber: nil, productId: self.pid, cid: id) { (re:ResponEntity) in
            ViewHelp.hideProgressActivity(containView: self.view)
            guard re.isSuccess() else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)
                return;
            }
            let productImges = re.getData() as? [ProductDetailImageTypeItemTo];
            
            var images = [SKPhoto]()
            
            if ( CollectionHelp.isEmpty(productImges) ) {
                ViewHelp.showTipsView(containView: self.view, tips: "该数据项为空")
                return;
            }
//            else{
//                let p=productImges![0]
//            KingfisherManager.shared.downloader.downloadImage(with: URL(string: Api.getImageUrl(Api.getImageUrl(p.URL ?? "") ))!, options: nil, progressBlock: nil) { (image:Image?, error:NSError?, imageURL:URL?, data:Data?) in
//                let httpUrl="http://"+StringHelp.split(imageURL!.absoluteString, "http://")[2] ;
//                LKMLog("====\(httpUrl)")
//                LKMLog("=====\(KingfisherManager.shared.cache.cachePath(forKey: httpUrl))")
//                var images = [SKLocalPhoto]()
//                let photo = SKLocalPhoto.photoWithImageURL(KingfisherManager.shared.cache.cachePath(forKey: httpUrl ))
////                let photo = SKPhoto.photoWithImageURL("http://120.77.8.217:1024/UpLoadFiles/20161010/2016101020382211.jpg");
//                images.append(photo)
//                let browser = SKPhotoBrowser(photos: images)
//                browser.initializePageIndex(0)
//                browser.view.backgroundColor=UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.25)
//                self.present(browser, animated: true, completion: {})
//
//                
//            }
//                return;
//            }
            
            
            if(productImges![0].URL!.hasSuffix(".pdf") ){
                var items=[String]();
                for p in productImges! {
//                    p.Txt_img = p.URL
                    items.append(p.Txt_img ?? "");
                    
                }
                
                ViewHelp.showSingleList(self, tips: "pdf", mItems: items, selectItem: "", onItemClick: { (index:Int) in
                    let p=productImges![index]
                    let urlimag=Api.getImageUrl(p.URL ?? "")
                    
                    
                    
                    if FileManager.default.fileExists(atPath: KingfisherManager.shared.cache.cachePath(forKey: urlimag)) {
                       self.showPDF(urlimag: urlimag)
                    }else{
                        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
                            let fileURL = URL(fileURLWithPath: KingfisherManager.shared.cache.cachePath(forKey: urlimag))
                            return (fileURL, [.createIntermediateDirectories])//[.removePreviousFile, .createIntermediateDirectories])
                        }
                        
                        //一开始会等回调才会有downloadProgress的 所以先显示
                        SVProgressHUD.showProgress(Float(0), status: "下载文件中")
                        self.curDownloadRequest = Alamofire.download(urlimag, to: destination).downloadProgress(closure: { (p:Progress) in
                            SVProgressHUD.showProgress(Float(p.fractionCompleted),status:"下载文件中");
                        }).response { response in
                            
                            self.curDownloadRequest=nil;
                            SVProgressHUD.dismiss()
                            
//                            if(response.response.)
                            if FileManager.default.fileExists(atPath: KingfisherManager.shared.cache.cachePath(forKey: urlimag)) {
                                self.showPDF(urlimag: urlimag)
                            }else{
                                ViewHelp.showTipsView(containView: self.view, tips: "下载失败")
                            }
                            
                        }
                    }
                    
                /*
                    imagev.kf.setImage(with: URL(string:urlimag )!, placeholder: Image(named: "PlaceHolderImage_small"), options: nil, progressBlock: nil) { (image, error, cacheType, imageURL) in
                        
//                    }
//                    
//                    KingfisherManager.shared.downloader.downloadImage(with: URL(string: Api.getImageUrl(p.URL ?? "") )!, options: nil, progressBlock: nil) { (image:Image?, error:NSError?, imageURL:URL?, data:Data?) in
                        
                        
                        LKMLog("=====\(error)")
                        
//
                        let httpUrl = imageURL!.absoluteString;
//                            "http://"+StringHelp.split(imageURL!.absoluteString, "http://")[2] ;
                        LKMLog("====\(httpUrl)")
                        
//                        let documentURL = URL(string:   KingfisherManager.shared.cache.cachePath(forKey: httpUrl)  )//Bundle.main.url(forResource: "Cupcakes", withExtension: "pdf")!
                        LKMLog("======\(KingfisherManager.shared.cache.cachePath(forKey: httpUrl ))")
                        let documentURL = NSURL.fileURL(withPath: KingfisherManager.shared.cache.cachePath(forKey: httpUrl ) )
//                        LKMLog("======\(KingfisherManager.shared.cache.cachePath(forKey: imageURL?.absoluteString ?? "" ))")
//                        let document = PDFDocument(fileURL: documentURL)!
//                        let readerController = PDFViewController.createNew(with: document)
//                        self.navigationController?.pushViewController(readerController, animated: true)
                        
//                        
                    }*/
                    
                    }, cancleRun: nil)
                
                return
            }
            
            for p in productImges! {
                let photo = SKPhoto.photoWithImageURL(Api.getImageUrl(p.URL ?? ""));
                //        photo.shouldCachePhotoURLImage = false // you can use image cache by true(NSCache)
                photo.shouldCachePhotoURLImage=true;
               // photo.caption=p.Txt_img//"1/2"//文字描叙
                LKMLog("====p.Txt_img \(p.Txt_img)")
                images.append(photo)
            }
            
            
            
            
            //        SKPhotoBrowserOptions.enableZoomBlackArea=false;//什么鬼?
            SKPhotoBrowserOptions.enableSingleTapDismiss = true  //单击 取消
            SKPhotoBrowserOptions.bounceAnimation        = true //反弹动画 当 appearing/dismissing
            
            SKPhotoBrowserOptions.displayStatusbar = false//顶部x 不自动取消
            //        SKPhotoBrowserOptions.displayToolbar = false//底部栏  不显示
            
            //        SKPhotoBrowserOptions.displayBackAndForwardButton = false   //底部栏 上面的左右按钮              // back / forward button will be hidden
            SKPhotoBrowserOptions.displayAction = false//底部栏上面的分析按钮
            
            SKPhotoBrowserOptions.disableVerticalSwipe = false
            
            SKPhotoBrowserOptions.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.25);//没作用的样子
            
            
            // 2. create PhotoBrowser Instance, and present.
            let browser = SKPhotoBrowser(photos: images)
            browser.initializePageIndex(0)
            browser.view.backgroundColor=UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.25)
            self.present(browser, animated: true, completion: {})
        }
        taskAlls.append(ts);


    }
    
    func showPDF(urlimag:String){
    
        let documentURL = NSURL.fileURL(withPath: KingfisherManager.shared.cache.cachePath(forKey: urlimag) )
        let document = PDFDocument(fileURL: documentURL)!
        let readerController = PDFViewController.createNew(with: document)
        
        Handler.post(  {
            //                            readerController.navigationItem = nil
            readerController.navigationItem.rightBarButtonItem = nil
            readerController.navigationItem.title = R.string.name
        })
        //暴力去掉右上角的打印按钮
        Handler.postDelayed(0.1, closure: {
            //                            readerController.navigationItem = nil
            readerController.navigationItem.rightBarButtonItem = nil
            readerController.navigationItem.title = R.string.name
        })
        
        Handler.postDelayed(0.2, closure: {
            //                            readerController.navigationItem = nil
            readerController.navigationItem.rightBarButtonItem = nil
            readerController.navigationItem.title = R.string.name
        })
        
        Handler.postDelayed(0.3, closure: {
            //                            readerController.navigationItem = nil
            readerController.navigationItem.rightBarButtonItem = nil
            readerController.navigationItem.title = R.string.name
        })
        Handler.postDelayed(0.5, closure: {
            //                            readerController.navigationItem = nil
            readerController.navigationItem.rightBarButtonItem = nil
            readerController.navigationItem.title = R.string.name
        })
        
        Handler.postDelayed(1, closure: {
            //                            readerController.navigationItem = nil
            readerController.navigationItem.rightBarButtonItem = nil
            readerController.navigationItem.title = R.string.name
        })
        self.navigationController?.pushViewController(readerController, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
//extension ProductDetailViewController: UIWebViewDelegate {
//    
//    func webViewDidStartLoad(_ webView: UIWebView) {
////        SVProgressHUD.setStatus("正在加载...")
//        
//        UIApplication.shared.isNetworkActivityIndicatorVisible = true
//    }
//    
//    func webViewDidFinishLoad(_ webView: UIWebView) {
////        SVProgressHUD.dismiss()
////这会等到图片全部加载完 里面的资源加载完
//        
//        
//        UIApplication.shared.isNetworkActivityIndicatorVisible = false
//    }
//    
//    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        
//        do{
//            var ss=StringHelp.split(request.url?.absoluteString , "ios_");
//            if(ss.count==2){
//                
//                ss=StringHelp.split(ss[1] , ":")
//                if ss[0] == "click_image_type" {
//                    let id=ss[1]
//                    onImageTypeClick(id);
//                    return false;
//                }
//            }
//        }catch let error as NSError {
//            print("Could not create audio player: \(error)")
//        }
//        return true;
//    }
//}

import Foundation
import SwiftyJSON

//lkm
class ProductShareTo: NSObject {
    
    var shareurl: String?;//"shareurl"
    var title: String?;//"title"
    var content: String?;//"content"
    
    //dict["data"].dictionaryObject  dict是JSON
    init?(jsons: [String: JSON]?) {
        super.init()
        if(jsons == nil){
            return nil
        }
        
        if let dict = jsons{
        self.shareurl = dict["shareurl"]?.string;//"shareurl"
        self.title = dict["title"]?.string;//"title"
        self.content = dict["content"]?.string;//"content"
    }
    }
    
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json: JSON)->[ProductShareTo?]{
        if let items = json.array {
            var results = [ProductShareTo?]()
            for item in items {
                let result = ProductShareTo(jsons: item.dictionary )
                //                if(result != nil){//空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                //                    results.append(result!)
                //                }
                results.append(result)
            }
            return results;
        }
        return [ProductShareTo?]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json: JSON)->Dictionary<String,ProductShareTo>{
        if let items = json.dictionary {
            var results = Dictionary<String,ProductShareTo>()//取值的时候本身就是可选类型啊,所以这里不用跟数组一样弄可选类型
            for (key, value)  in items {
                let result = ProductShareTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,ProductShareTo>()
    }
    
    
    
    
}



import Foundation
import SwiftyJSON

//lkm
class ProductDetailTo: NSObject {
    
    var productDetail: ProductDetailToDetailTo?;//
    var pictype: String?;//
    var prored: String?;//
    
    //dict["data"].dictionaryObject  dict是JSON
    init?(jsons: [String: JSON]?) {
        super.init()
        if(jsons == nil){
            return nil
        }
        
        if let dict = jsons{
//        LKMLog(dict)
        
            self.productDetail = ProductDetailToDetailTo.init(jsons: dict["promodel"]?.dictionary )//(jsons: ( dict["data"] as? [String:Any])?["promodel"] as? [String:Any] ??  [String:Any]()) //dict["promodel"]?.string;//
//        self.pictype = dict["pictype"]?.string;//
//        self.prored = dict["prored"]?.string;//
    }
    }
    
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json: JSON)->[ProductDetailTo?]{
        if let items = json.array {
            var results = [ProductDetailTo?]()
            for item in items {
                let result = ProductDetailTo(jsons: item.dictionary )
                //                if(result != nil){//空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                //                    results.append(result!)
                //                }
                results.append(result)
            }
            return results;
        }
        return [ProductDetailTo?]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json: JSON)->Dictionary<String,ProductDetailTo>{
        if let items = json.dictionary {
            var results = Dictionary<String,ProductDetailTo>()//取值的时候本身就是可选类型啊,所以这里不用跟数组一样弄可选类型
            for (key, value)  in items {
                let result = ProductDetailTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,ProductDetailTo>()
    }
    

    
    
}
import Foundation
import SwiftyJSON

//lkm
class ProductDetailToDetailTo: NSObject {
    
    var num_Good: Int?;//"0"
    var num_Bad: Int?;//"0"
    var sellId: String?;//""
    var channelId: Int?;//"582"
    var click: Int?;//"0"
    var goodsAddTime: String?;//"别墅|轻钢别墅|小别墅|木别墅|木屋|度假屋"
    var goodsAttrList: String?;//"2016/10/11 9:01:02"
    var goodsBrandId: Int?;//"0"
    var goodsCode: String?;//"VM289"
    var goodsCostPrice: Int?;//"0"
    var goodsDetail: String?;//""
    var goodsDetail_e: String?;//"<div>\n\tClient: Yuvraj Dada</div>\n<div>\n\tType of Structure: Residential</div>\n<div>\n\tLocation: Ludhiana, Punjab</div>\n<div>\n\tStatus: Completed</div>\n<div>\n\t&nbsp;</div>\n<div>\n\tDescription: 5BHK Residential Home with Built Up area: 5620 Sq ft, Deck &amp; Verandah Area: 1570 Sq Ft. Our scope was the steel structure with Board fitting.</div>\n"
    var goodsKeys: String?;//"别墅|轻钢别墅|小别墅|木别墅|木屋|度假屋"
    var goodsMarketPrice: Int?;//"0"
    var goodsName: String?;//"轻钢别墅"
    var goodsName_e: String?;//""
    var goodsPoint: Int?;//"0"
    var goodsSellPrice: Int?;//"0"
    var goodsService: String?;//""
    var goodsService_e: String?;//""
    var goodsSKUCode: String?;//""
    var goodsSKUList: String?;//""
    var goodsStartUpTime: String?;//"2016/10/11 9:01:02"
    var goodsStock: Int?;//"0"
    var goodsTypeId: Int?;//"38"
    var goodsUnit: String?;//"件"
    var goodsUnit_e: String?;//"piece"
    var goodsWarningLine: Int?;//"0"
    var goodsWeight: Int?;//"0"
    var id: Int?;//"116"
    var isHot: Int?;//"0"
    var isMsg: Int?;//"1"
    var isRed: Int?;//"0"
    var isSlide: Int?;//"0"
    var isStartUp: Int?;//"1"
    var isTop: Int?;//"0"
    var seo_description: String?;//""
    var seo_keywords: String?;//""
    var seo_title: String?;//""
    var sort: Int?;//"1"
    var proimg: String?;//"/UpLoadFiles/20161010/2016101020382211.jpg"
    var sku1: String?;//""
    var sku2: String?;//""
    var sku3: String?;//""
    var sku4: String?;//""
    var sku5: String?;//""
    var keyws: String?;//"别墅|轻钢别墅|小别墅|木别墅|木屋|度假屋"
    var iskeep: Int?;//"0"
    var Source: String?;//"http://120.77.8.217:1024/webApp/html/productDetail.html?pid=116"
    
    //dict["data"].dictionaryObject  dict是JSON
    init?(jsons: [String: JSON]?) {
        super.init()
        if(jsons == nil){
            return nil
        }
        
        if let dict = jsons{
        
//        self.num_Good = dict["num_Good"]?.int;//"0"
//        self.num_Bad = dict["num_Bad"]?.int;//"0"
//        self.sellId = dict["sellId"]?.string;//""
//        self.channelId = dict["channelId"]?.int;//"582"
//        self.click = dict["click"]?.int;//"0"
//        self.goodsAddTime = dict["goodsAddTime"]?.string;//"别墅|轻钢别墅|小别墅|木别墅|木屋|度假屋"
//        self.goodsAttrList = dict["goodsAttrList"]?.string;//"2016/10/11 9:01:02"
//        self.goodsBrandId = dict["goodsBrandId"]?.int;//"0"
//        self.goodsCode = dict["goodsCode"]?.string;//"VM289"
//        self.goodsCostPrice = dict["goodsCostPrice"]?.int;//"0"
//        self.goodsDetail = dict["goodsDetail"]?.string;//""
//        self.goodsDetail_e = dict["goodsDetail_e"]?.string;//"<div>\n\tClient: Yuvraj Dada</div>\n<div>\n\tType of Structure: Residential</div>\n<div>\n\tLocation: Ludhiana, Punjab</div>\n<div>\n\tStatus: Completed</div>\n<div>\n\t&nbsp;</div>\n<div>\n\tDescription: 5BHK Residential Home with Built Up area: 5620 Sq ft, Deck &amp; Verandah Area: 1570 Sq Ft. Our scope was the steel structure with Board fitting.</div>\n"
//        self.goodsKeys = dict["goodsKeys"]?.string;//"别墅|轻钢别墅|小别墅|木别墅|木屋|度假屋"
//        self.goodsMarketPrice = dict["goodsMarketPrice"]?.int;//"0"
//        self.goodsName = dict["goodsName"]?.string;//"轻钢别墅"
//        self.goodsName_e = dict["goodsName_e"]?.string;//""
//        self.goodsPoint = dict["goodsPoint"]?.int;//"0"
//        self.goodsSellPrice = dict["goodsSellPrice"]?.int;//"0"
//        self.goodsService = dict["goodsService"]?.string;//""
//        self.goodsService_e = dict["goodsService_e"]?.string;//""
//        self.goodsSKUCode = dict["goodsSKUCode"]?.string;//""
//        self.goodsSKUList = dict["goodsSKUList"]?.string;//""
//        self.goodsStartUpTime = dict["goodsStartUpTime"]?.string;//"2016/10/11 9:01:02"
//        self.goodsStock = dict["goodsStock"]?.int;//"0"
//        self.goodsTypeId = dict["goodsTypeId"]?.int;//"38"
//        self.goodsUnit = dict["goodsUnit"]?.string;//"件"
//        self.goodsUnit_e = dict["goodsUnit_e"]?.string;//"piece"
//        self.goodsWarningLine = dict["goodsWarningLine"]?.int;//"0"
//        self.goodsWeight = dict["goodsWeight"]?.int;//"0"
//        self.id = dict["id"]?.int;//"116"
//        self.isHot = dict["isHot"]?.int;//"0"
//        self.isMsg = dict["isMsg"]?.int;//"1"
//        self.isRed = dict["isRed"]?.int;//"0"
//        self.isSlide = dict["isSlide"]?.int;//"0"
//        self.isStartUp = dict["isStartUp"]?.int;//"1"
//        self.isTop = dict["isTop"]?.int;//"0"
//        self.seo_description = dict["seo_description"]?.string;//""
//        self.seo_keywords = dict["seo_keywords"]?.string;//""
//        self.seo_title = dict["seo_title"]?.string;//""
//        self.sort = dict["sort"]?.int;//"1"
        self.proimg = dict["proimg"]?.string;//"/UpLoadFiles/20161010/2016101020382211.jpg"
//        self.sku1 = dict["sku1"]?.string;//""
//        self.sku2 = dict["sku2"]?.string;//""
//        self.sku3 = dict["sku3"]?.string;//""
//        self.sku4 = dict["sku4"]?.string;//""
//        self.sku5 = dict["sku5"]?.string;//""
//        self.keyws = dict["keyws"]?.string;//"别墅|轻钢别墅|小别墅|木别墅|木屋|度假屋"
        self.iskeep = dict["iskeep"]?.int;//"0"
//        self.Source = dict["Source"]?.string;//"http://120.77.8.217:1024/webApp/html/productDetail.html?pid=116"
    }
    }
    
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json: JSON)->[ProductDetailToDetailTo?]{
        if let items = json.array {
            var results = [ProductDetailToDetailTo?]()
            for item in items {
                let result = ProductDetailToDetailTo(jsons: item.dictionary )
                //                if(result != nil){//空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                //                    results.append(result!)
                //                }
                results.append(result)
            }
            return results;
        }
        return [ProductDetailToDetailTo?]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json: JSON)->Dictionary<String,ProductDetailToDetailTo>{
        if let items = json.dictionary {
            var results = Dictionary<String,ProductDetailToDetailTo>()//取值的时候本身就是可选类型啊,所以这里不用跟数组一样弄可选类型
            for (key, value)  in items {
                let result = ProductDetailToDetailTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,ProductDetailToDetailTo>()
    }
    
    
    
}

